<template>
  <!-- 页面-规则管理 -->
  <div 
   :class="{'innerPageTable-box-OneTwo': !useTableSearchBar}"
    class="RuleManage-page innerPageTable-out-flex">
    <!-- 搜索区域 -->
    <SelfAdaption v-if="!useTableSearchBar">
      <Form
        :model="searchForm"
        ref="ruleSearchForm"
        slot="adaption-bar"
        label-position="top"
        class="ivu-form-no-margin-bottom"
        inline
      >
        <!-- 规则编码 -->
        <Form-item prop="code" :label="$t('module.dataPermission.ruleCode')">
          <Input
            type="text"
            :maxlength="30"
            v-model.trim="searchForm.code"
            :placeholder="$t('module.dataPermission.warning.enterRuleCode')"
            @on-enter="search"
          ></Input>
        </Form-item>

        <!-- 规则名称 -->
        <Form-item prop="name" :label="$t('module.dataPermission.ruleName')">
          <Input
            type="text"
            :maxlength="30"
            v-model.trim="searchForm.name"
            :placeholder="$t('module.dataPermission.warning.enterRuleName')"
            @on-enter="search"
          ></Input>
        </Form-item>

        <!-- 适用对象 -->
        <Form-item prop="target" :label="$t('module.dataPermission.shieldingObject')">
          <Select
            v-model="searchForm.target"
           :placeholder="$t('module.dataPermission.warning.enterShieldingObject')"
           clearable>
            <Option v-for="(value, name) in objectList" :value="name" :key="name">{{ value }}</Option>
          </Select>
        </Form-item>

        <!-- 查询\重置按钮 -->
        <Form-item prop="button" class="search-solt-btn">
          <RPButton optType="search" @click="search" />
          <RPButton optType="reset" @click="reset" />
        </Form-item>
      </Form>
    </SelfAdaption>
    <InnerPageTable ref="ruleTable" :config="tableConfig">
      <!-- handler bar 查询/重置-->
      <!--
      <div slot="handle-bar">
        <RPButton optType="search" @click="search" />
        <RPButton optType="reset" @click="reset" />
      </div>
      -->
      <!-- table bar 添加-->
      <div slot="table-bar">
        <RPButton optType="create" @click="add" v-permission="'ADD_PERMISSION_RULE'" />
        <RPButton optType="batch" @click="deleted(null)" v-permission="'DELETE_PERMISSION_RULE'" />
      </div>
      <Form
        v-if="useTableSearchBar"
        :model="searchForm"
        ref="ruleSearchForm"
        slot="table-search-bar"
        label-position="top"
        class="ivu-form-no-margin-bottom"
        inline
      >
        <!-- 规则编码 -->
        <Form-item prop="code">
          <Input
            type="text"
            :maxlength="30"
            v-model.trim="searchForm.code"
            :placeholder="$t('module.dataPermission.warning.enterRuleCode')"
            clearable
            @on-enter="search"
            @on-blur="search"
            @on-clear="search"
          ></Input>
        </Form-item>

        <!-- 规则名称 -->
        <Form-item prop="name">
          <Input
            type="text"
            :maxlength="30"
            v-model.trim="searchForm.name"
            :placeholder="$t('module.dataPermission.warning.enterRuleName')"
            clearable
            @on-enter="search"
            @on-blur="search"
            @on-clear="search"
          ></Input>
        </Form-item>

        <!-- 适用对象 -->
        <Form-item prop="target">
          <Select 
          v-model="searchForm.target"
          style="width: 180px;"
          :placeholder="$t('module.dataPermission.warning.enterShieldingObject')"
          @on-change="search(1)"
          clearable>
            <Option v-for="(value, name) in objectList" :value="name" :key="name">{{ value }}</Option>
          </Select>
        </Form-item>
      </Form>
    </InnerPageTable>
  </div>
</template>
<script>
import dataPermissionAPI from '@/api/dataPermissionAPI.js'
import { ruleColumns } from './columns.js'
import PermissionRuleEdit from './PermissionRuleEdit.vue'
import RuleDimensionList from './RuleDimensionList.vue'
import locales from './locales.js'
import { CoreModuleName } from '@/const.js'
import valueSetAPI from '@/api/valueSetAPI.js'

export default {
  name: 'data-permission',
  mixins: [locales],
  data() {
    return {
      searchForm: {
        tenantCode: '',
        name: '',
        code: '',
        target: ''
      },
      objectList: {},
      controlLevelList: {}
    }
  },
  computed: {
    tableConfig() {
      return { loadDataFn: this.queryRuleList, columnsFn: ruleColumns.bind(this), autoFirst: false }
    }
  },
  created: function() {
    this.init()
  },
  mounted() {},
  methods: {
    // 获取规则列表数据
    queryRuleList({ responseProcess, param }) {
      dataPermissionAPI.queryRuleList(param).then(data => {
        if (data && data.records) {
          data.records = this.$root.$options.filters['selection-disabled'](data.records)
        }
        responseProcess(data)
      })
    },
    async init() {
      let { userInfo } = $store.state[CoreModuleName]
      if (!userInfo) return
      // 当前租户
      this.searchForm.tenantCode = userInfo.tenantCode

      const [objectData, levelData] = await Promise.all([
        valueSetAPI.getValueSetByCode('SYS_DATA_AUTH_OBJECT'),
        valueSetAPI.getValueSetByCode('SYS_DATA_AUTH_LEVEL')
      ])

      // 初始化适用对象
      this.initObject(objectData)
      // 初始化控制层级
      this.initControlLevel(levelData)
      // 查询列表
      this.search()
    },
    // 初始化适用对象
    initObject(data) {
      let list = {}
      for (const obj of data) {
        list[obj.vsiKey] = obj.vsiValue
      }
      this.objectList = list
    },
    // 初始化控制层级
    initControlLevel(data) {
      for (const level of data) {
        this.controlLevelList[level.vsiKey] = level.vsiValue
      }
    },
    search(page = 1) {
      this.$refs['ruleTable'].load(this.searchForm, page)
    },
    reset() {
      this.$refs['ruleSearchForm'].resetFields()
      this.search(1)
    },
    getOperations(permissionRule) {
      let operations = [
        {
          type: 'icon',
          icon: 'md-create',
          text: this.$t('common.edit'),
          permission: 'EDIT_PERMISSION_RULE',
          handle: () => {
            this.edit(permissionRule)
          }
        },
        {
          type: 'icon',
          icon: 'ios-settings',
          text: this.$t('module.dataPermission.assignDataPermission'),
          permission: 'ASSIGN_DATA_PERMISSION',
          handle: () => {
            this.assign(permissionRule)
          }
        },
        {
          type: 'icon',
          icon: 'ios-trash',
          text: this.$t('common.delete'),
          hidden: permissionRule.enabled == 1,
          permission: 'DELETE_PERMISSION_RULE',
          handle: () => {
            this.deleted(permissionRule)
          }
        }
      ]
      return operations
    },
    add() {
      new this.$pageModal(
        PermissionRuleEdit,
        {
          props: {
            tenantCode: this.searchForm.tenantCode
          }
        },
        data => {
          data && this.search()
        }
      )
    },
    edit(permissionRule) {
      new this.$pageModal(
        PermissionRuleEdit,
        {
          props: {
            tenantCode: this.searchForm.tenantCode,
            permissionRule: permissionRule,
            ruleCode: permissionRule.code,
            ruleId: permissionRule.id
          }
        },
        data => {
          data && this.search(this.$refs.ruleTable.param.pageNum)
        }
      )
    },
    assign(permissionRule = {}) {
      new this.$sidelipPage(
        RuleDimensionList,
        {
          props: {
            tenantCode: this.searchForm.tenantCode,
            ruleCode: permissionRule.code,
            controlLevel: permissionRule.level,
          },
          cache: true // 开启弹窗缓存
        },
        data => {}
      )
    },
    deleted(permissionRule) {
      let selectedIds
      if (permissionRule) {
        selectedIds = [permissionRule.id]
      } else {
        selectedIds = this.getSelectedIds()
        if (selectedIds.length == 0) {
          this.$message.error({
            content: this.$t('module.dataPermission.warning.selectRule')
          })
          return
        }
      }
      new $confirm(this.$t('module.dataPermission.warning.ensureToDelete'), this).then(() => {
        dataPermissionAPI
          .deleteRule(selectedIds)
          .then(res => {
            this.$message.success({
              content: this.$t('common.deleteSuccess'),
              duration: 3
            })
            this.search()
          })
          .catch(data => {
            this.$message.error({
              content: data.message,
              duration: 3
            })
          })
      })
    },
    getSelectedIds() {
      let list = this.$refs['ruleTable'].getSelectioned() || []
      let ids = []
      for (let u of list) {
        ids.push(u.id)
      }
      return ids
    }
  },
  async beforeRouteLeave(to, from, next) {
    // 读取任务队列里的任务，执行完再next
    const tasks = window?.$app?.routeChangeTasks || []
    while (tasks.length) {
      const task = tasks.shift()
      await task()
    }
    next()
  }
}
</script>
<style lang="less">
.RuleManage-page {
  .ivu-table {
    .ivu-table-fixed-right {
      .ivu-table-fixed-body {
        .ivu-table-tbody {
          tr {
            .ivu-table-cell {
              width: 109px !important;
            }
          }
        }
      }
    }
  }
}
</style>
